package net.takela.common.spring.mybatis.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author baboy
 * create at 2023/1/22
 */
@MappedJdbcTypes(JdbcType.ARRAY)
@MappedTypes(List.class)
public class LongArrayTypeHandler extends BaseTypeHandler<Object> {

	
    /**
     * 
     */
    @Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			Object parameter, JdbcType jdbcType)
			throws SQLException {
		String s = null;
		try {
			if (parameter != null && parameter instanceof List){
				StringBuffer sb = new StringBuffer();
				List list = (List)parameter;
				String sep = ",";
				for (int j = 0, n = list.size(); j< n; j++){
					String obj = String.valueOf(list.get(j));
					if(j > 0){
						sb.append(sep);
					}
					sb.append(obj);
				}
				if (sb.length()>0){
					s = sb.toString();
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		ps.setString(i, s);
	}

	
    /**
     * 
     */
    @Override
	public Object getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		String s = rs.getString(columnName);
		return getResult(s);
	}

	
    /**
     * 
     */
    @Override
	public Object getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		String s = rs.getString(columnIndex);
		return getResult(s);
	}

	
    /**
     * 
     */
    @Override
	public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String s = cs.getString(columnIndex);
		return getResult(s);
	}
    /**
     * 
     */
	public Object getResult(String s){
		if(s == null || s.trim().length()==0) {
			return null;
		}
		try{
			String[] a = s.trim().split(",|;|，|；|\\s+");
			List<Long> obj = new ArrayList<>();
			for (String i : a){
				obj.add(Long.parseLong(i));
			}
			return obj;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

}
